package com.fyy.exception.exception;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;

/**
 * @Author fyy
 * @Description 统一异常处理
 * @Date 2020/6/16 14:45
 */
@RestControllerAdvice
public class ExceptionAdvice {

    private static Logger logger = LoggerFactory.getLogger(ExceptionAdvice.class);

    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public ResultBean defaultException(HttpServletRequest request, Exception e){
        logger.error("系统发生异常：{},请及时处理！",e.getMessage());
        return ResultBean.builder()
                .code(ResultEnum.EXCEPTION.getCode())
                .message(ResultEnum.EXCEPTION.getMessage())
                .build();
    }

    @ExceptionHandler(value = MyException.class)
    @ResponseBody
    public ResultBean myException(HttpServletRequest request,MyException e){
        e.printStackTrace();
        Integer code = e.getCode();
        String message = e.getMessage();

        if(null == e.getCode()){
            code = ResultEnum.EXCEPTION.getCode();
        }

        if (null == e.getMessage()){
            message = ResultEnum.EXCEPTION.getMessage();
        }

        return ResultBean.builder()
                .code(code)
                .message(message)
                .build();
    }

}
